// pages/discovery/articleDetail/index.js
const common = require('../../../public.js')
const config = require('../../../config')
let innerAudioContext = wx.createInnerAudioContext(); //创建音频实例
var startPoint
Page({

    data: {
      // 
      isOverShare: true, //全局分享标识请勿删除
        articleId: '',
        articleDetail: {},
        commentList: [],
        focusList: [],
        commentValue: '',
        pubUserId: '',
        commentId: '',
        commentPlachold: '我来说几句',
        textareaForce: false,
        userInfo: null,
        isLoadingBusy: false,
        title: null,
        storeName: null,
        createTime: 0,
        storeImg: null,
        buttonTop: 0,
        buttonLeft: 0,
        windowHeight: '',
        windowWidth: '',
        musicUrl: '',
        isPlay: true,
        tieBianLeft: false,
        tieBianRight: false,
        tieBian: false,
        Badwords:['妈', 'sb', 'SB', '爸', '国', '党', '傻']
    },

    copy: function (e) {
        var that = this;
        var text = e.currentTarget.dataset.text;
        let texts = text.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n').replace(/<br\/?>/gi, '\n').replace(/<[^>/]+>/g, '').replace(/(\n)?<\/([^>]+)>/g, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ').replace(/<\/?(img)[^>]*>/gi, '').replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&#39;/g, "\'").replace(/&quot;/g, "\"").replace(/<\/?.+?>/g, "")

        console.log(e);
        wx.setClipboardData({
            data: texts,
            success: function (res) {
                // wx.hideToast();    //打开可不显示提示框
                wx.getClipboardData({
                    success(res) {
                        // console.log(res.data) // data

                    }
                })
            }
        })
    },

    onLoad: function (options) {
        let that = this
        this.data.articleId = options.id ? options.id :640
        this.setData({
            storeName: options.storeName,
            createTime: parseInt(options.createTime),
            storeImg: options.storeImg
        })
        if(options.title){
            const title = options.title
            this.setData({
                title
            })
            wx.setNavigationBarTitle({
                title
            })
        }

        common.getLocalUserInfo(function (success, data) {
            if (success) {
                that.setData({
                    userInfo: data.user,
                    token: data.token,
                }, function () {
                    that.getFocusList()
                    that.getArticleDetail()
                    that.getCommentList()
                })
            } else {
                that.getArticleDetail()
                that.getCommentList()
            }
        })
    },
    // 
    btn_Suspension_clicks() {
        this.setData({
            buttonLeft: this.data.buttonLeft - 30,
            tieBianLeft: false,
            tieBian: false
        })
    },
    btn_Suspension_clickL() {
        this.setData({
            buttonLeft: this.data.buttonLeft + 30,
            tieBianRight: false,
            tieBian: false
        })
    },
    //可拖动悬浮按钮点击事件
    btn_Suspension_click: function (e) {
        var that = this
        var musicUrl = that.data.musicUrl
        innerAudioContext.src = musicUrl;
        innerAudioContext.autoplay = true

        if (that.data.isplay) {
            console.log("停止")
            innerAudioContext.stop()
            that.setData({
                isplay: false
            })
        } else {
            console.log("播放")
            innerAudioContext.play();
            that.setData({
                isplay: true
            })
        }

    },
    //以下是按钮拖动事件
    buttonStart: function (e) {
        console.log(e.touches[0].clientX, "开始的点")    //开始拖动的x轴
        startPoint = e.touches[0]//获取拖动开始点
    },
    buttonMove: function (e) {
        console.log(e.touches[0].clientX, "结束的点")    //开始拖动的x轴
        var endPoint = e.touches[e.touches.length - 1]//获取拖动结束点
        //计算在X轴上拖动的距离和在Y轴上拖动的距离
        var translateX = endPoint.clientX - startPoint.clientX  //
        var translateY = endPoint.clientY - startPoint.clientY
        startPoint = endPoint//重置开始位置
        var buttonTop = this.data.buttonTop + translateY
        var buttonLeft = this.data.buttonLeft + translateX
        console.log(buttonLeft, "buttonLeft")
        // console.log(this.data.windowWidth)

        // //判断是移动否超出屏幕
        if (buttonLeft + 50 >= this.data.windowWidth) {
            buttonLeft = this.data.windowWidth - 50;
            this.setData({
                tieBianLeft: true,
                tieBian: true,
            })
            console.log("jinlai")
        } else if (buttonLeft <= 0) {
            buttonLeft = 0;
            this.setData({
                tieBianRight: true,
                tieBian: true,
            })
        } else {
            this.setData({
                tieBianRight: false,
                tieBianLeft: false,
                tieBian: false,

            })
        }
        // if (buttonLeft<=0){
        //  buttonLeft=0;
        //  this.setData({
        //     tieBianRight:true,
        //     tieBian:true,
        // })
        // }
        if (buttonTop <= 0) {
            buttonTop = 0
        }
        if (buttonTop + 50 >= this.data.windowHeight) {
            buttonTop = this.data.windowHeight - 50;
        }
        console.log(this.data.tieBian)
        this.setData({
            buttonTop: buttonTop,
            buttonLeft: buttonLeft
        })
    },
    buttonEnd: function (e) {
    },
    cancleCommentPraise(id) {
        let that = this
        let tempJson = {
            userId: (that.data.userInfo && that.data.userInfo.id) ? that.data.userInfo.id : '',
            token: that.data.token,
            commentId: id
        }
        common.post('/storeArticle/cancleStoreArticleCommentPraise', tempJson, function (res) {
            if (res.status === 200) {
                that.getCommentList()
            }
        })
    },
    commitPraise(id) { // 点赞
        const that = this
        let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            commentId: id
        }
        common.post('/storeArticle/saveStoreArticleCommentPraise', tempJson, function (res) {
            if (res.status == 200) {
                that.getCommentList()
            }
        })
    },
    praiseAction(e) {
        const id = e.currentTarget.dataset.item.id
        const userPraiseFlag = e.currentTarget.dataset.item.userPraiseFlag
        if (userPraiseFlag) {
            this.cancleCommentPraise(id)
        } else {
            this.commitPraise(id)
        }
    },
    onChange(e) {
        let {
            value
        } = e.detail

        this.setData({
            commentValue: value
        })
    },
    getArticleDetail() {
        this.setData({
            isLoadingBusy: true
        })
        const that = this
        const tempJson = {
            userId: (that.data.userInfo && that.data.userInfo.id) ? that.data.userInfo.id : '',
            token: that.data.token ? that.data.token : '',
            articleId: that.data.articleId
        }
        common.post("/storeArticle/getStoreArticleDetail", tempJson, function (res) {
            if (res.status === 200) {

                var jsonDa = JSON.stringify(res.data.content).replace(/<img/gi, "<img class='richImg'style='width:auto!important;height:auto!important;max-height:100%;width:100%;'")
                    .replace(/<div/gi, "<div class='divClass'")
                    .replace(/<span/gi, "<span class='spanClass'")
                // jsonDa = '<div class="div_class">'+jsonDa+'</div>'

                that.setData({
                    articleDetail: res.data,
                    musicUrl: res.data.articleAudio,
                    articleContent: JSON.parse(jsonDa),
                    storeName: res.data.storeName,
                    title: res.data.title,
                    createTime: parseInt(res.data.createTime),
                    storeImg: res.data.storeImg
                })
            } else {
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                isLoadingBusy: false
            })
        })
    },
    toBuy(e) {
        let {
            item
        } = e.currentTarget.dataset
        let url = null
        switch (this.data.articleDetail.itemType) {
            //1普通商品 2零元购 3团购商品 4惠特汇商品 5店铺活动 6抽奖
            case 1: // 1普通商品
                common.gotoGoodsPage(item)
                break;
            case 2: // 2零元购 
                url = '/packageC/pages/Zero/Des/index?id=' + item.id + '&name=' + item.title
                break;
            case 3: // 3团购商品
                url = '/pages/crowd/index/index?id=' + item.id
                break;
            case 4: // 4惠特汇商品 
                common.gotoGoodsPage(item, '&isVip=true')
                break;
            case 5: // 5店铺活动
                url = '/pages/Activity/actDes/index?id=' + item.id + '&name=' + item.title + '&isVip=true'
                break;
            case 6: // 6抽奖
                url = '/pages/draw/index?drawId=' + item.id
                break;
            default:
                break;
        }
        if (url) {
            wx.navigateTo({
                url: url
            })
        }
    },
    getCommentList() {
        const that = this
        const tempJson = {
            articleId: that.data.articleId,
            userId: (that.data.userInfo && that.data.userInfo.id) ? that.data.userInfo.id : '',
            token: that.data.token ? that.data.token : '',
            pageNum: 1,
            pageSize: '',
        }
        common.post("/storeArticle/getStoreArticleCommentList", tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    commentList: res.data
                })
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    getFocusList() {
        let that = this
        let tempJson = {
            articleId: that.data.articleId,
            pageNum: 1,
            pageSize: 10,
        }
        common.post("/storeArticle/getStoreArticleFocusList", tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    focusList: res.data
                })
            }
        })
    },
    commentSave() { //点击键盘评论按钮
        let that = this
        if (that.data.commentId) { // 有commentid是二级评论
            that.replyComment()
        } else {
            that.replyArticle()
        }
    },
    clickReply(e) { // 点击评论中的回复
        let that = this
        let {
            pubuserid,
            commentid,
            pubusername
        } = e.currentTarget.dataset
        that.setData({
            pubUserId: pubuserid,
            commentId: commentid,
            commentPlachold: '@' + pubusername + '：'
        })
    },
    replyArticle() { // 直接评论文章
        if (this.data.commentValue === null || this.data.commentValue.length === 0) {
            common.showToast('您没有输入任何文字')
            return
        }
        if(common.filter_methods(this.data.commentValue,this.data.Badwords)){
            common.showToast('含有违规词，请重新输入')
            return
        }
        // 不是飞羊小程序不走云函数校验
        if (!config.isFyApp) {
            this.submitArticleComment()
        }
        const that = this
       
        that.submitArticleComment()
        // wx.cloud.callFunction({
        //     name: 'ContentCheck',
        //     config: {
        //         env: wx.cloud.DYNAMIC_CURRENT_ENV
        //       },
        //     data: {
        //         txt: that.data.commentValue
        //     },
        //     success(res) {
        //         console.log(res,"6666666666666666")
        //         if (res.result.errCode == 87014) {
        //             common.showToast('文字违规，请重新输入')
        //         } else {
        //             that.submitArticleComment()
        //         }
        //     },
        //     fail(err) {
        //         console.log(err,"uuuuuuuuuuu")
        //         common.showToast('文字违规，请重新输入666668888')
        //     }
        // })
    },
    submitArticleComment() {
        const that = this
        // 合规
        let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            articleId: that.data.articleId,
            content: that.data.commentValue,
        }
        common.post('/storeArticle/saveStoreArticleComment', tempJson, function (res) {
            if (res.status === 200) {
                that.getCommentList()
                that.clearReplyInfo()
                common.showToast('评论成功', 'success')
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    replyComment(e) { // 回复某一条回复
        if (this.data.commentValue === null || this.data.commentValue.length === 0) {
            common.showToast('您没有输入任何文字')
            return
        }
        if(common.filter_methods(this.data.commentValue,this.data.Badwords)){
            common.showToast('含有违规词，请重新输入')
            return
        }
      
        if (!config.isFyApp) {
            this.submitReplyComment()
        }

        const that = this
        
       
        that.submitReplyComment()
        // wx.cloud.callFunction({
        //     name: 'ContentCheck',
        //     data: {
        //         txt: that.data.commentValue
        //     },
        //     success(res) {
        //         console.log(res,"4444555555555555555")
        //         if (res.result.errCode == 87014) {
        //             console.log(res.errCode)
        //             common.showToast('文字违规，请重新输入')
        //         } else {
        //             // 合规
        //             that.submitReplyComment()
        //         }
        //     },
        //     fail(err) {
        //         console.log(err,"66666666666666666666666")
        //         common.showToast('文字违规，请重新输入')
        //     }
        // })
    },
    submitReplyComment() {
        const that = this
        let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            pubUserId: that.data.userInfo.id,
            commentId: that.data.commentId,
            content: that.data.commentValue,
        }
        common.post("/storeArticle/saveStoreArticleCommentChat", tempJson, function (res) {
            if (res.status == 200) {
                that.getCommentList()
                that.clearReplyInfo()
                common.showToast('评论成功', 'success')
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    clearReplyInfo() {
        this.setData({
            commentValue: '',
            pubUserId: "",
            commentId: '',
            commentPlachold: '我来说几句'
        })
    },
    onShareAppMessage: function () {
      console.log('执行了---');
        let that = this
        common.post("/storeArticle/saveStoreArticleShareNum", {
            articleId: that.data.articleId
        },
            function (res) {
                console.log(res)
            })
        return {
            title: that.data.articleDetail.title,
            path: '/pages/discovery/articleDetail/index?id=' + that.data.articleId,
            imageUrl: that.data.articleDetail.imgUrl,
        }
    },
    textareaBindblur: function () {
        this.setData({
            textareaForce: false
        })
    },
    textareaBindfocus: function () {
        this.setData({
            textareaForce: true
        })
    },
    collectAction() {
        if (!this.data.articleDetail.focusFlag) {
            this.focusStoreArticle()
        }
    },
    focusStoreArticle() {
        const that = this
        const param = {
            userId: that.data.userInfo.id ? that.data.userInfo.id : '',
            token: that.data.token ? that.data.token : '',
            articleId: that.data.articleId
        }
        common.post('/storeArticle/focusStoreArticle', param, function (res) {
            if (res.status === 200) {
                that.getArticleDetail()
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    //获取全部列表
    getAllComment() {
        wx.navigateTo({
            url: '/pages/discovery/comment/index?itemId=' + this.data.articleId,
        })
    },
})